<?php

namespace Modules\User\Http\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\User\Entities\Address;

class AddressController extends Controller
{
    /**
     * 获取用户地址列表
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $addresses = $user->addresses()->get();
        $current_address_id = $user->current_address_id;
        return compact('addresses', 'current_address_id');
    }

    public function show(Address $address)
    {
        return $address;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = $request->user();
        $address = $user->addresses()->updateOrCreate(['id' => $request->id], $request->all());

        // 将最近的地址设置为默认地址
        $user->current_address_id = $address->id;
        $user->save();

        return $address->id;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\address  $address
     * @return \Illuminate\Http\Response
     */
    public function destroy(Address $address)
    {
        return response()->json($address->delete());
    }

    /**
     * use Illuminate\Http\Request;
     */
    public function setCurrentAddress(Request $request)
    {
        $request->validate([
            'id' => 'required'
        ]);

        $user = $request->user();
        $user->current_address_id = $request->id;
        $user->save();

        return $request->id;
    }
}
